export default {
  namespaced: true,
  
  mutations: {
    addToCart(state,value) {
      const findResult = state.cart.find(item => item.goods_id == value.goods_id)
      if(!findResult) {
        state.cart.push(value)
      }else {
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    //更新购物车中勾选状态
   updateGoodsState(state,goods) {
      const findResult = state.cart.find(item => item.goods_id == goods.goods_id)
      if(findResult) {
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    //更新商品的数量
    updateGoodsCount(state,goods) {
      const findResult = state.cart.find(item => item.goods_id == goods.goods_id)
      if(findResult) {
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    //删除商品
    removeGoodsById(state,goods) {
      state.cart = state.cart.filter(item => item.goods_id != goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    //更新商品状态
    updateAllGoodsState(state,newState) {
      state.cart.forEach(item => item.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    }
  },
  
  state: () =>({
    cart: JSON.parse(uni.getStorageSync('cart')  || '[]')
  }),
  
  getters: {
    //计算购物车中商品总数
    total(state) {
      return state.cart.reduce((total,item) => total += item.goods_count,0)
    },
    //计算已勾选的商品数量
    checkedCount(state) {
      return state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count,0)
    },
    //计算结算金额
    checkedGoodsAmount(state) {
      return state.cart.filter(item => item.goods_state).reduce((total,item) => total += item.goods_count * item.goods_price,0).toFixed(2)
    }
  }
}